package top.lyjwn.todo.common.redis;

import com.alibaba.fastjson2.JSONObject;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;

public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T> {


    private Class<T> tClass;

    public void settClass(Class<T> tClass) {
        this.tClass = tClass;
    }

    private Class<T> getTClass() {
        return tClass;
    }

    @Override
    public byte[] serialize(T value) throws SerializationException {
        if (value == null) {
            return new byte[0];
        }
        return JSONObject.toJSONString(value).getBytes(StandardCharsets.UTF_8);
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length <= 0) {
            return null;
        }
        String str = new String(bytes, StandardCharsets.UTF_8);
        JSONObject jsonObject = JSONObject.parseObject(str);
        return jsonObject.toJavaObject(getTClass());
    }
}
